package logic

import (
	"context"
	"user/common"
	"user/models"

	"user/internal/svc"
	"user/pb/user"

	"github.com/zeromicro/go-zero/core/logx"
)

type CreateUserLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewCreateUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *CreateUserLogic {
	return &CreateUserLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// CreateUser 创建用户
func (l *CreateUserLogic) CreateUser(in *user.UserInfo) (*user.UserInfo, error) {
	encryptPass := common.Md5Encrypt(in.Password)
	result, err := l.svcCtx.UserModel.Insert(l.ctx,
		&models.User{Name: in.Name, Password: encryptPass, Mobile: in.Mobile, Email: in.Email, Status: common.UserStatusEnabled})
	if err != nil {
		return nil, err
	}

	userID, err := result.LastInsertId()
	if err != nil {
		return nil, err
	}

	in.Id = userID
	l.Logger.Infof("create user: %v", in)
	return &user.UserInfo{Id: userID}, nil
}
